import requests
from enum import Enum
from datetime import datetime
import time

from datacol.tool import get_previous_week_range, get_max_version_data


# 定义时间范围枚举类
class TimeWindow(Enum):
    MINUTE = 2  # 分钟聚合
    HOUR = 3  # 小时聚合
    DAY = 4  # 按天聚合
    WEEK = 5  # 按周聚合
    MONTH = 6  # 按月聚合

# 定义崩溃、ANR卡顿的枚举类
class MetricType(Enum):
    CRASH = 8  # 崩溃（crash）
    ANR = 4  # ANR
    YELLOW_LAG = 31  # 卡顿黄色点(需要配合subTupes 31)
    GREEN_POINT = 52  # 卡顿绿色点(需配合subTypes 401)
    BLUE_POINT = 52  # 卡顿蓝色点(需配合subTypes 402)

class SubType(Enum):
    YELLOW = 81
    GREEN = 401
    BLUE = 402

# 定义操作类型
class FilterOperator(Enum):
    EQUAL = "EQ"
    NOT_EQUAL = "NE"
    GREATER_THAN = "GT"
    GREATER_EQUAL = "GE"
    LESS_THAN = "LT"
    LESS_EQUAL = "LE"
    IN = "IN"
    OR = "OR"

def get_crash_and_anr_data(
        start_date_str: str,
        end_date_str: str,
        time_window: TimeWindow = TimeWindow.WEEK,
        metric_type: MetricType = MetricType.CRASH,
        app_versions: list = None,
        product_id: str = "b99545917b"
):
    """
    获取 Bugly 数据

    参数:
        start_date_str (str): 开始日期，格式如 "2025-06-15 00:00:00"
        end_date_str (str): 结束日期，格式如 "2025-07-15 23:59:59"
        time_window (TimeWindow): 时间窗口类型，默认为按周聚合
        metric_type (MetricType): 指标类型，默认为崩溃数据
        app_versions (list): 应用版本列表，如 ["3.9.1"]，默认为None
        product_id (str): 产品ID

    返回:
        dict: Bugly API 的响应数据
    """
    # 验证日期格式
    try:
        datetime.strptime(start_date_str, "%Y-%m-%d %H:%M:%S")
        datetime.strptime(end_date_str, "%Y-%m-%d %H:%M:%S")
    except ValueError:
        raise ValueError("日期格式必须为 'YYYY-MM-DD HH:MM:SS'")

    # 转换为时间戳
    start_time = int(time.mktime(datetime.strptime(start_date_str, "%Y-%m-%d %H:%M:%S").timetuple()))
    end_time = int(time.mktime(datetime.strptime(end_date_str, "%Y-%m-%d %H:%M:%S").timetuple()))

    headers = {
        'Authorization': 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTYwMTQxNDkuNjIyMTA4LCJpYXQiOjE3NTM0MjIxNDkuNjIyMTA4LCJpc3MiOiJ0ZW5jZW50IiwiY3VzdG9tIjp7InVpbiI6IjMwODU1NTMyMzE2NzI5OTMiLCJzVG9rZW4iOiJmMTE0MmYzOTVjMTMyZTNlODQ5YWU2ZGI3YTRhZmE0OCIsImNpZCI6IjdjYTRiMzI0NmFhZTQ5OTEzY2M0NjE3ZTczOGZhYWNjIn19.gD91itZ1MEJ2gh1ykm7SMen1pRAg0Wxw7r2U7JTSJ8tKYT9rYq61VoV4nskNPY4H0VFfwZYYEWqzGQISTqL8vQ',
        'X-ProductID': product_id,
    }

    # 构造 POST 请求的 JSON 数据
    json_data_post = {
        'form_list': {
            'time_window': time_window.value,
            'start_date_str': start_date_str,
            'end_date_str': end_date_str,
            'start_time': start_time,
            'end_time': end_time,
            'filters': [
                {
                    'name': 'app_version',
                    'values': app_versions,  # 默认值
                    'operator': 'OR',
                }
            ],
        },
    }

    # 获取 token
    response = requests.post(
        'https://bugly.tds.qq.com/v5/api/url-token/get',
        headers=headers,
        json=json_data_post
    )

    token = response.json()['token']

    # 构造 GET 请求的 JSON 数据
    json_data_getdashboard = {
        'productId': product_id,
        'type': metric_type.value,
        'token': token,
    }

    # 获取数据
    response = requests.post(
        'https://bugly.tds.qq.com/v5/trpc/trpc.rmonitor.metrics_server.GetMetrics/GetDashboardData',
        headers=headers,
        json=json_data_getdashboard,
    )

    return response.json()


def get_bugly_carton_data(
        start_date_str: str,
        end_date_str: str,
        app_versions: list = None,
        min_time_cost_ms: int = 800,
        metric_type: MetricType = MetricType.YELLOW_LAG,
        sub_type: SubType = SubType.YELLOW,
        time_window: TimeWindow = TimeWindow.WEEK,
        product_id: str = "b99545917b"
):
    """
    获取Bugly卡顿数据

    参数:
        start_date_str (str): 开始日期，格式如"2025-07-07 00:00:00"
        end_date_str (str): 结束日期，格式如"2025-07-13 23:59:59"
        app_versions (list): 应用版本列表，如["3.8.88"]
        min_time_cost_ms (int): 最小耗时阈值(毫秒)
        metric_type (MetricType): 指标类型
        sub_type (SubType): 卡顿子类型
        time_window (TimeWindowType): 时间窗口类型,默认是按周聚合
        product_id (str): 产品ID

    返回:
        dict: API响应数据
    """
    # 验证日期格式并转换为时间戳
    try:
        start_dt = datetime.strptime(start_date_str, "%Y-%m-%d %H:%M:%S")
        end_dt = datetime.strptime(end_date_str, "%Y-%m-%d %H:%M:%S")
        start_ts = str(int(start_dt.timestamp()))
        end_ts = str(int(end_dt.timestamp()))
    except ValueError:
        raise ValueError("日期格式必须为'YYYY-MM-DD HH:MM:SS'")

    headers = {
        'Authorization': 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTYwMTQxNDkuNjIyMTA4LCJpYXQiOjE3NTM0MjIxNDkuNjIyMTA4LCJpc3MiOiJ0ZW5jZW50IiwiY3VzdG9tIjp7InVpbiI6IjMwODU1NTMyMzE2NzI5OTMiLCJzVG9rZW4iOiJmMTE0MmYzOTVjMTMyZTNlODQ5YWU2ZGI3YTRhZmE0OCIsImNpZCI6IjdjYTRiMzI0NmFhZTQ5OTEzY2M0NjE3ZTczOGZhYWNjIn19.gD91itZ1MEJ2gh1ykm7SMen1pRAg0Wxw7r2U7JTSJ8tKYT9rYq61VoV4nskNPY4H0VFfwZYYEWqzGQISTqL8vQ',
        'X-ProductID': product_id,
    }

    # 构建过滤器
    filters = [
        {
            'name': 'event_time',
            'values': [start_ts],
            'operator': FilterOperator.GREATER_EQUAL.value
        },
        {
            'name': 'event_time',
            'values': [end_ts],
            'operator': FilterOperator.LESS_EQUAL.value
        },
        {
            'name': 'time_cost',
            'values': [str(min_time_cost_ms)],
            'operator': FilterOperator.GREATER_THAN.value
        }
    ]

    # 添加版本过滤器（如果有提供版本）
    if app_versions:
        filters.append({
            'name': 'app_version',
            'values': app_versions,
            'operator': FilterOperator.OR.value
        })

    # 构建请求数据
    json_data_post = {
        'form_list': {
            'standard_time_range': {
                'date_type': 'event_time',
                'time_window_type': time_window.value,
                'date_value': [start_date_str, end_date_str],
            },
            'filters': filters,
            'time_window': time_window.value,
        }
    }

    # 获取token
    token_response = requests.post(
        'https://bugly.tds.qq.com/v5/api/url-token/get',
        headers=headers,
        json=json_data_post
    )
    token = token_response.json()['token']

    # 构建查询数据
    json_data_getdashboard = {
        'productId': product_id,
        'type': metric_type.value,
        'subTypes': [sub_type.value],
        'token': token,
    }

    # 获取数据
    data_response = requests.post(
        'https://bugly.tds.qq.com/v5/trpc/trpc.rmonitor.metrics_server.GetMetrics/GetDashboardData',
        headers=headers,
        json=json_data_getdashboard,
    )

    return data_response.json()
# 使用示例
if __name__ == "__main__":
    import yaml
    with open("config.yaml", "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)
    productids = config['apps']
    last_week_start, last_week_end = get_previous_week_range()
    print(last_week_start + "   " + last_week_end)
    result = {
        f'padCartonRate': 0.0,
        f'padCartonRateStr': "0.0‰",  # 学习机
        f'inkCartonRate': 0.0,
        f'inkCartonRateStr': "0.0‰",  # 学练机
        'list': []
    }

    # for item in productids:
    #     try:
    #         appId = item['appId']
    #         max_version = get_max_version_data(last_week_start,last_week_end,appId)
    #         #crash_data = get_crash_and_anr_data(last_week_start,last_week_end,app_versions=[max_version],product_id=item)
    #         #anr_data = get_crash_and_anr_data(last_week_start,last_week_end,app_versions=[max_version],product_id=item,metric_type=MetricType.ANR)
    #         carton_data = get_bugly_carton_data(last_week_start,last_week_end,app_versions=[max_version],product_id=appId)
    #     except ValueError:
    #         print(f'错误')
    #         continue
    #     result['list'].append({
    #         'appName': item['name'],
    #         'appVersion': max_version,
    #         f'appCartonRate': carton_data['data']['dataPoints'],
    #         f'appCartonRateStr': f"{float(carton_data['data']['dataPoints'] * 1000):.1f}‰",
    #     })

    print(result)
    max_version = get_max_version_data(last_week_start, last_week_end, "b99545917b")
    crash_data = get_crash_and_anr_data(last_week_start, last_week_end, app_versions=[max_version], product_id="b99545917b")
    print(crash_data)


